﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
using WindowsFormsApp1.SQlite;

namespace WindowsFormsApp1
{
    public partial class frmResume : Form
    {
        private List<frmWorkHistory> frmWorkHistories = new List<frmWorkHistory>();
        public frmResume()
        {
            InitializeComponent();
            addWorkHistory();
            adjustControlPositionAndSize();

            // 为TextBox控件注册Validating事件
            tbPhone.Validating += PhoneTextBox_Validating;
            tbIdentificationNumber.Validating += IdentificationNumberTextBox_Validating;
            tbHeight.TextChanged += (object sender, EventArgs e) => { tbHeight.Text = Regex.Replace(tbHeight.Text, @"[^\d]", ""); };
        }
        /// <summary>
        /// 清空界面所有值。一般用于新增简历时
        /// </summary>
        public void clearEmptyAllControl()
        {
            tbName.Tag = null;
            pictureBoxHead.Tag = null;
            pictureBoxHead.Image = null;
            tbAddress.Text = "";
            tbDegree.Text = "";
            tbEmail.Text = "";
            tbHeight.Text = "";
            tbIdentificationNumber.Text = "";
            tbLastCompany.Text = "";
            tbLastIndustry.Text = "";
            tbLastPosition.Text = "";
            tbMajor.Text = "";
            tbName.Text = "";
            tbPhone.Text = "";
            tbUniversity.Text = "";
            dateTimePickerBirth.Value = DateTime.Now;
            for (int i = 0; i < frmWorkHistories.Count; i++)
            {
                frmWorkHistories[i].clearEmptyAllControl();
            }
        }
        private void btnImportHead_Click(object sender, EventArgs e)
        {
            OpenFileDialog fileDialog = new OpenFileDialog();
            fileDialog.Title = "选择图片文件";
            fileDialog.Filter = "图片文件 (*.jpg;*.jpeg;*.png)|*.jpg;*.jpeg;*.png|所有文件 (*.*)|*.*";
            fileDialog.Multiselect = false;
            DialogResult result = fileDialog.ShowDialog();

            if (result == DialogResult.OK)
            {
                string filePath = fileDialog.FileName;

                pictureBoxHead.SizeMode = PictureBoxSizeMode.StretchImage;
                pictureBoxHead.Image = Image.FromFile(filePath);

                string destPath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "headImage");
                if (!Directory.Exists(destPath)) Directory.CreateDirectory(destPath);
                string destFileName = GuidTo16String() + fileDialog.SafeFileName;
                destPath += "\\"+destFileName;
                File.Copy(filePath, destPath, true); // 第三个参数表示如果目标文件已存在，是否覆盖它
                pictureBoxHead.Tag = "\\headImage\\" + destFileName;

            }
        }
        private string GuidTo16String()
        {
            string guid = Guid.NewGuid().ToString("N");
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < guid.Length; i += 2)
            {
                sb.Append(guid[i]);
                if (sb.Length >= 16)
                    break;
            }
            string str = sb.ToString();
            return str;
        }
        private void addWorkHistory()
        {
            int additionalHeight = 40;
            frmWorkHistory fwh = new frmWorkHistory();
            fwh.TopLevel = false;
            fwh.Parent = groupBoxWorkHistory;
            if (frmWorkHistories.Count == 0)
                fwh.Location = new Point(5, additionalHeight);
            else
                fwh.Location = new Point(5, frmWorkHistories[frmWorkHistories.Count-1].Location.Y + fwh.Height + lbWorkHistory.Height + 5);
            fwh.Show();
            frmWorkHistories.Add(fwh);
        }
        /// <summary>
        /// 注意先调用moveButton，再调佣resizeGroupBox
        /// </summary>
        private void resizeGroupBox()
        {
            groupBoxWorkHistory.Height = btnAddWork.Location.Y + btnAddWork.Height + 10;
        }
        /// <summary>
        /// 移动新增工作经验和删除工作经验按钮
        /// </summary>
        private void moveAddAndDeleteWorkButton()
        {
            if (frmWorkHistories.Count == 0) return;
            
            btnAddWork.Location = new Point(btnAddWork.Location.X, frmWorkHistories[frmWorkHistories.Count - 1].Location.Y + frmWorkHistories[frmWorkHistories.Count - 1].Height);
            btnDeleteWork.Location = new Point(btnDeleteWork.Location.X, frmWorkHistories[frmWorkHistories.Count - 1].Location.Y + frmWorkHistories[frmWorkHistories.Count - 1].Height);
        }
        /// <summary>
        /// 移动保存简历按钮
        /// </summary>
        private void moveSaveResumeButton()
        {
            btnSaveResume.Location = new Point(btnSaveResume.Location.X, groupBoxWorkHistory.Location.Y + groupBoxWorkHistory.Height + 10);
        }

        private void btnAddWork_Click(object sender, EventArgs e)
        {
            addWorkHistory();
            adjustControlPositionAndSize();
        }

        private void btnDeleteWork_Click(object sender, EventArgs e)
        {
            if (frmWorkHistories.Count == 0) return;
            if (frmWorkHistories.Count == 1)
            {
                //不删除，但清空
                frmWorkHistories[0].clearEmptyAllControl();
                return;
            }
            frmWorkHistories[frmWorkHistories.Count - 1].Close();
            frmWorkHistories.RemoveAt(frmWorkHistories.Count - 1);
            adjustControlPositionAndSize();

        }
        private void adjustControlPositionAndSize()
        {
            //根据计算的逻辑，这个方法调用顺序不能变
            moveAddAndDeleteWorkButton();
            resizeGroupBox();
            moveSaveResumeButton();
        }
        private void PhoneTextBox_Validating(object sender, CancelEventArgs e)
        {
            TextBox textBox = sender as TextBox;
            if (textBox != null)
            {
                string phoneRegex = @"^1[3-9]\d{9}$";

                if (!Regex.IsMatch(textBox.Text, phoneRegex))
                {
                    // 如果手机号码无效，则显示错误消息
                    textBox.BackColor = Color.Salmon; // 背景颜色变化作为警告
                    //e.Cancel = true; // 设置为true以取消输入
                }
                else
                {
                    // 如果符合格式，恢复正常背景颜色
                    textBox.BackColor = Color.White;
                }
            }
        }
        private void IdentificationNumberTextBox_Validating(object sender, CancelEventArgs e)
        {
            TextBox textBox = sender as TextBox;
            if (textBox != null)
            {

                if (!CheckNumber(textBox.Text.Trim()))
                {
                    textBox.BackColor = Color.Salmon; // 背景颜色变化作为警告
                }
                else
                {
                    // 如果符合格式，恢复正常背景颜色
                    textBox.BackColor = Color.White;
                }
            }
        }
        /// <summary>
        /// 二代身份证都是18位
        /// </summary>
        /// <param name="id">身份证号</param>
        /// <returns></returns>
        public bool CheckNumber(string id)
        {
            //数字验证
            long num = 0;
            try
            {
                if (id.Length != 18)
                {
                    return false;
                }
                if (long.TryParse(id.Remove(17), out num) == false || num < Math.Pow(10, 16) || long.TryParse(id.Replace('x', '0').Replace('X', '0'), out num) == false)
                {
                    return false;
                }
                //省份验证
                string address = "11x22x35x44x53x12x23x36x45x54x13x31x37x46x61x14x32x41x50x62x15x33x42x51x63x21x34x43x52x64x65x71x81x82x91";
                if (address.IndexOf(id.Remove(2)) == -1)
                {
                    return false;
                }
                //生日验证
                string time = id.Substring(6, 8).Insert(6, "-").Insert(4, "-");
                DateTime birthday = new DateTime();
                if (DateTime.TryParse(time, out birthday) == false)
                {
                    return false;
                }
                //校验码验证
                string[] varifyCode = ("1,0,x,9,8,7,6,5,4,3,2").Split(',');
                string[] wiMap = ("7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2").Split(',');
                char[] Ai = id.Remove(17).ToCharArray();
                int sum = 0;
                for (int i = 0; i < 17; i++)
                {
                    sum += int.Parse(wiMap[i]) * int.Parse(Ai[i].ToString());
                }
                int wiIndex = -1;
                Math.DivRem(sum, 11, out wiIndex);
                if (varifyCode[wiIndex] != id.Substring(17, 1).ToLower())
                {
                    return false;
                }
            }
            catch (Exception ex)
            {
                return false;
            }
            return true;//符合GB11643-1999标准
        }
        /// <summary>
        /// 保存前检查输入合法性、必填项
        /// </summary>
        private bool checkInput()
        {
            if(tbName.Text.Trim() == string.Empty)
            {
                MessageBox.Show("姓名是必填项!");
                return false;
            }
            if (tbPhone.Text.Trim() == string.Empty)
            {
                MessageBox.Show("电话是必填项!");
                return false;
            }
            if (tbAddress.Text.Trim() == string.Empty)
            {
                MessageBox.Show("住址是必填项!");
                return false;
            }
            if (tbIdentificationNumber.Text.Trim() == string.Empty)
            {
                MessageBox.Show("身份证是必填项!");
                return false;
            }
            if (!CheckNumber(tbIdentificationNumber.Text.Trim()))
            {
                MessageBox.Show("身份证号码错误!");
                return false;
            }
            if(tbAddress.Text.Trim().Length > 100)
            {
                MessageBox.Show("现住址超长，不能超过100个字!");
                return false;
            }
            if (tbDegree.Text.Trim().Length > 32)
            {
                MessageBox.Show("最高学历学位超长，不能超过32个字!");
                return false;
            }
            if (tbEmail.Text.Trim().Length > 64)
            {
                MessageBox.Show("邮箱超长，不能超过64字母!");
                return false;
            }
            if (tbLastCompany.Text.Trim().Length > 32)
            {
                MessageBox.Show("公司名称超长，不能超过32个字!");
                return false;
            }
            if (tbLastIndustry.Text.Trim().Length > 32)
            {
                MessageBox.Show("所属行业超长，不能超过32个字!");
                return false;
            }
            if (tbLastPosition.Text.Trim().Length > 32)
            {
                MessageBox.Show("职位名称超长，不能超过32个字!");
                return false;
            }
            if (tbMajor.Text.Trim().Length > 64)
            {
                MessageBox.Show("专业名称超长，不能超过64个字!");
                return false;
            }
            if (tbName.Text.Trim().Length > 32)
            {
                MessageBox.Show("姓名超长，不能超过32个字!");
                return false;
            }
            if (tbUniversity.Text.Trim().Length > 64)
            {
                MessageBox.Show("大学名称超长，不能超过64个字!");
                return false;
            }
            return true;
        }

        public string ImageToBase64(PictureBox pictureBox)
        {
            // 确保PictureBox中有图片
            if (pictureBox.Image == null)
            {
                return "";
            }

            using (MemoryStream ms = new MemoryStream())
            {
                ImageFormat format = ImageFormat.Jpeg;
                pictureBox.Image.Save(ms, format);
                return Convert.ToBase64String(ms.ToArray());
            }
        }

        private void btnSaveResume_Click(object sender, EventArgs e)
        {
            if (!checkInput()) return;
            PersonModel personModel = new PersonModel();
            personModel.address = tbAddress.Text.Trim();
            personModel.birth = dateTimePickerBirth.Value.ToString("yyyy-MM-dd");
            personModel.cardNo = tbIdentificationNumber.Text.Trim();
            personModel.email = tbEmail.Text.Trim();
            personModel.gender = cmbGender.Text.Trim();
            personModel.height = tbHeight.Text.Trim();
            personModel.highestDegree = tbDegree.Text.Trim();
            personModel.lastCompany = tbLastCompany.Text.Trim();
            personModel.lastIndusty = tbLastIndustry.Text.Trim();
            personModel.lastPosition = tbLastPosition.Text.Trim();
            personModel.major = tbMajor.Text.Trim();
            personModel.name = tbName.Text.Trim();
            personModel.phone = tbPhone.Text.Trim();
            personModel.photo = pictureBoxHead.Tag?.ToString();
            personModel.school = tbUniversity.Text.Trim();

            if(tbName.Tag != null)
            {
                personModel.guid = tbName.Tag.ToString();
            }
            else
            {
                tbName.Tag = GuidTo16String();
                personModel.guid = tbName.Tag.ToString();
            }

            int order = 0;
            for (int i = 0; i < frmWorkHistories.Count; i++)
            {
                if(frmWorkHistories[i].CheckInput() == -1)
                {
                    MessageBox.Show("工作经验没有填完整");
                    return;
                }
                if (frmWorkHistories[i].CheckInput() == 0)
                {
                    continue;
                }
                if (frmWorkHistories[i].CheckInput() == 1)
                {
                    WorkHistoryModel whm = frmWorkHistories[i].getWorkHistory();
                    whm.order = order;
                    ++order;
                    personModel.workHistoryModels.Add(whm);
                }
            }

            try
            {
                if(DbOperate.Instance.AddOrUpdatePerson(personModel))
                {
                    MessageBox.Show("保存成功");
                }
                else
                {
                    MessageBox.Show("保存失败");
                }
            }
            catch(Exception ex)
            {
                MessageBox.Show("发生异常:" + ex.Message);
                return;
            }
        }

        public void editResume(PersonModel personModel)
        {
            tbName.Tag = personModel.guid;
            tbAddress.Text = personModel.address;
            tbDegree.Text = personModel.highestDegree;
            tbEmail.Text = personModel.email;
            tbHeight.Text = personModel.height;
            tbIdentificationNumber.Text = personModel.cardNo;
            tbLastCompany.Text = personModel.lastCompany;
            tbLastIndustry.Text = personModel.lastIndusty;
            tbLastPosition.Text = personModel.lastPosition;
            tbMajor.Text = personModel.major;
            tbName.Text = personModel.name;
            tbPhone.Text = personModel.phone;
            tbUniversity.Text = personModel.school;
            cmbGender.Text = personModel.gender;
            if(personModel.photo != string.Empty)
            {
                try
                {
                    pictureBoxHead.SizeMode = PictureBoxSizeMode.StretchImage;
                    pictureBoxHead.Image = Image.FromFile(AppDomain.CurrentDomain.BaseDirectory + personModel.photo);
                    pictureBoxHead.Tag = personModel.photo;
                }
                catch(Exception ex)
                {
                    MessageBox.Show("头像图片异常,:" + ex.Message);
                }
                
            }
            

            

            DateTime selectedDate;
            // 尝试解析时间字符串
            if (DateTime.TryParse(personModel.birth, out selectedDate))
            {
                dateTimePickerBirth.Value = selectedDate;
            }
            #region 增加或删除工作经验的窗体，使得窗体和工作经验匹配
            int diff = personModel.workHistoryModels.Count - frmWorkHistories.Count;
            if(diff > 0)
            {
                //增加窗体
                for (int i = 0; i < diff; i++)
                {
                    addWorkHistory();
                    adjustControlPositionAndSize();
                }
            }
            else if(diff < 0)
            {
                diff = Math.Abs(diff);
                for (int i = 0; i < diff; i++)
                {
                    btnDeleteWork_Click(null, null);
                }
            }
            #endregion
            for (int i = 0; i < personModel.workHistoryModels.Count; i++)
            {
                if(i < frmWorkHistories.Count)
                {
                    frmWorkHistories[i].editWorkHistory(personModel.workHistoryModels[i]);
                }
            }
        }

        public void deleteResume()
        {
            if (tbName.Tag != null)
            {
                DbOperate.Instance.DeletePerson(tbName.Tag.ToString());
                clearEmptyAllControl();
            }
        }
    }
}
